package com.wechat.demo.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class CheckUtil {

    public static String token = "weixin";

    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[]{token,timestamp,nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0;i<arr.length;i++){
            content.append(arr[i]);
        }

        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr =toHex(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        content = null;
        return tmpStr!=null ? tmpStr.equals(signature) : false;
    }

    private static String toHex(byte[] bytes) {
        String str = "";
        for (byte b : bytes) {
            char[] chars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            char[] temp = new char[2];
            temp[0] = chars[(b >>> 4) & 0x0F];
            temp[1] = chars[b & 0x0F];

            str += new String(temp);
        }
        return str;
    }

}
